<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Real-time Log Viewer</title>
    <style>
      body {
        padding-bottom: 30px;
      }
      .status-indicator {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 5px;
      }

      .status-indicator.connected {
        background-color: green;
      }

      .status-indicator.disconnected {
        background-color: red;
      }

      /* 修改控制开关容器的样式 */
      .controls {
        position: fixed;
        top: 20px;
        right: 20px;
        background-color: rgba(255, 255, 255, 0.9);
        padding: 10px;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        z-index: 1000;
      }

      /* 添加鼠标悬停效果 */
      .controls:hover {
        background-color: rgba(255, 255, 255, 1);
      }

      /* 调整状态指示器容器的样式，避免与固定定位的控制开关重叠 */
      .status-container {
        margin-right: 200px;
      }
    </style>
    <script>
      document.addEventListener('DOMContentLoaded', function () {
        const logElement = document.getElementById('log')
        const statusElement = document.getElementById('status')
        const statusIndicatorElement = document.getElementById('status_indicator')
        const autoScrollCheckbox = document.getElementById('autoScroll')

        // 自动根据当前访问地址构建WebSocket URL
        const wsProtocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://'
        const wsHost = window.location.hostname
        const wsPort = 3000 // 你的WebSocket服务端口
        const ws = new WebSocket(`${wsProtocol}${wsHost}:${wsPort}`)

        ws.onopen = function () {
          statusElement.textContent = 'Connected'
          statusIndicatorElement.classList.remove('disconnected')
          statusIndicatorElement.classList.add('connected')
        }

        ws.onclose = function () {
          statusElement.textContent = 'Disconnected'
          statusIndicatorElement.classList.remove('connected')
          statusIndicatorElement.classList.add('disconnected')
        }

        ws.onmessage = function (event) {
          logElement.innerHTML = event.data + '<br>'
          /* 只在复选框被选中时执行自动滚动 */
          if (autoScrollCheckbox.checked) {
            document.querySelector('body').scrollIntoView(false)
          }
          console.log(event.data)
        }

        ws.onerror = function (error) {
          console.error('WebSocket Error:', error)
        }
      })
    </script>
  </head>
  <body>
    <div class="status-container">
      <span id="status_indicator" class="status-indicator disconnected"></span>
      <span id="status">Disconnected</span>
    </div>
    <div class="controls">
      <label>
        <input type="checkbox" id="autoScroll" checked />
        自动滚动到最新日志
      </label>
    </div>
    <h1>Log:</h1>
    <pre id="log"></pre>
  </body>
</html>
